﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace MS.INV.Exports
{
    public class ExcelBase : IDisposable
    {
        public event EventHandler PercentProgress;

        public ApplicationClass xlsApp;
        public Workbook workbook;
        public Worksheet currSheet;
        string _FilePath = "";

        public ExcelBase(string FilePath)
        {
            _FilePath = FilePath;
            InitApp();
        }

        private void InitApp()
        {
            xlsApp = new ApplicationClass();
            if (File.Exists(_FilePath))
                workbook = xlsApp.Workbooks.Open(_FilePath, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing);
            else
                workbook = xlsApp.Workbooks.Add(Type.Missing);

            currSheet = workbook.Sheets[1] as Worksheet; //First worksheet
            //currSheet.Name = "App Data";

            xlsApp.Visible = false;
        }

        public void Dispose()
        {
            Release();
            GC.SuppressFinalize(this);
        }

        ~ExcelBase()
        {
            //Release();
        }

        private void Release()
        {
            workbook.Close(true, Type.Missing, Type.Missing);
            workbook = null;
            xlsApp.Quit();
            xlsApp = null;
        }

        public bool IsString(DataColumn dc)
        {
            if (dc.DataType == Type.GetType("System.String")) return true;
            return false;
        }

        public bool IsNumber(DataColumn dc)
        {
            if (dc.DataType == Type.GetType("System.Int32") ||
                dc.DataType == Type.GetType("System.Decimal") ||
                dc.DataType == Type.GetType("System.Double"))
                return true;
            return false;
        }

        public void Save(string Path)
        {
            xlsApp.DisplayAlerts = false;
            workbook.SaveAs(Path,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                XlSaveAsAccessMode.xlNoChange,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing);

            //this.Dispose();
        }

        public void SetPercent(int Percent)
        {
            if (this.PercentProgress != null)
                this.PercentProgress(Percent, new EventArgs());
        }
    }
}
